package cz.incad.psh.pshassign.server;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.util.EntityUtils;

/**
 *
 * @author Alberto Hernandez
 */
public class Invenio {

    private Logger logger = Logger.getLogger(this.getClass().getName());

    public String update(String xml) throws Exception {
        HttpClient httpclient = new DefaultHttpClient();
        httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

        HttpPost httppost = new HttpPost(Options.getOption("bibupload", "adress"));
        httppost.setHeader("User-Agent", Options.getOption("bibupload", "user_agent"));


        File f = File.createTempFile("upload", ".tmp");

        BufferedWriter bw = new BufferedWriter(new FileWriter(f));
        bw.write(xml);
        bw.close();


        FileBody bin = new FileBody(f);
        StringBody sb = new StringBody(xml);
        StringBody mode = new StringBody("-c");

        MultipartEntity reqEntity = new MultipartEntity();
        reqEntity.addPart("file", bin);
        reqEntity.addPart("mode", mode);
        httppost.setEntity(reqEntity);


        logger.log(Level.INFO, "executing request " + httppost.getRequestLine());
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity resEntity = response.getEntity();

        StatusLine status = response.getStatusLine();
        if(status.getStatusCode()!=200){
            logger.log(Level.SEVERE, "Unable to save to Invenio. " + httppost.getRequestLine() + " returned: ", status);
            throw new Exception("Unable to save to Invenio. " + 
                    httppost.getRequestLine() + " returned: " + 
                    status);
        }
        String s = status.toString();
        if (resEntity != null) {
            s += EntityUtils.toString(resEntity);
        }
        if (resEntity != null) {
            resEntity.consumeContent();
        }

        httpclient.getConnectionManager().shutdown();
        f.delete();
        //logger.log(Level.INFO, s);
        return s;
    }
}
